from threading import Thread

import two_pc


def create_thread(num):
    # 创建协调者线程
    coordinator = two_pc.Coordinator()  # 实例化

    # 创建参与者线程
    for i in range(0, num - 1):  # TODO：可扩展为线程池的方式
        participant = two_pc.Participant(i, coordinator)
        coordinator.participant_list.append(participant)  # 添加到协调者拥有的参与者列表
        participant_i = Thread(target=participant.start, name=f'participant_{i}')
        participant_i.thread_id = i
        coordinator.thread_list.append(participant_i)
        participant_i.setDaemon(True)  # 守护线程
        # participant_i.start()  # 参与者线程启动

    coordinator_thread = Thread(target=coordinator.start, name=f'coordinator_{num - 1}')  # 设置线程执行协调者工作
    coordinator.thread_list.append(coordinator_thread)
    coordinator.index = len(coordinator.thread_list) - 1
    coordinator.thread_id = coordinator.index
    coordinator_thread.setDaemon(True)  # 守护线程
    coordinator_thread.start()  # 协调者线程启动

    for i in range(0, num - 1):
        coordinator.thread_list[i].start()  # 启动参与者线程
    for i in range(0, num):
        coordinator.thread_list[i].join()


def main(num):
    create_thread(num)  # 创建参与者和协调者，开始工作


if __name__ == '__main__':
    participant_num = int(input("请输入工作线程个数(默认最后一个为协调者)："))
    main(participant_num)
